package cn.jtool.dig.server.timer;

import cn.jtool.dig.common.model.Session;
import cn.jtool.dig.common.netty.CtxUtils;
import cn.jtool.dig.common.netty.SessionManager;
import cn.jtool.dig.server.comm.real.RealAttrKey;
import cn.jtool.dig.server.dao.entity.LogTraffic;
import cn.jtool.dig.server.dao.entity.PortMapping;
import cn.jtool.dig.server.service.LogService;
import com.google.common.collect.Lists;
import io.netty.channel.ChannelHandlerContext;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
public class LogTrafficTask {

    @Resource
    private LogService logService;


    public void run(){
        List<Session> sessions = SessionManager.getSession(Session.SessionType.REAL);
        if(CollectionUtils.isNotEmpty(sessions)){
            List<LogTraffic> logTraffics = Lists.newArrayList();
            for (Session session : sessions) {
                LogTraffic logTraffic = new LogTraffic();
                ChannelHandlerContext channelHandlerContext = session.getChannelHandlerContext();
                PortMapping portMapping = CtxUtils.getAttribute(channelHandlerContext, RealAttrKey.OUTWARD_DIG_CONF);
                logTraffic.setPortMappingId(portMapping.getId());
                logTraffic.setLicenseId(portMapping.getLicenseId());
                logTraffic.setRecBytes(session.getTrafficBySegment(Session.TrafficDir.REC, true));
                logTraffic.setSendBytes(session.getTrafficBySegment(Session.TrafficDir.SEND, true));
                logTraffics.add(logTraffic);
            }
            this.logService.saveLogTraffic(logTraffics);
        }
    }

}
